Skip to main content

Lesson 1: Java Basics

1. Variables and Data Types

What are Variables?

Variables are containers used to store data.

  • In Java, every variable has a type that defines the kind of data it can hold.

Common Data Types in Java:

Data TypeSizeDescriptionExample
int4 bytesStores integersint age = 25;
double8 bytesStores decimalsdouble price = 19.99;
char2 bytesStores single characterschar grade = 'A';
StringVariesStores a sequence of charactersString name = "John";
boolean1 bitStores true or false valuesboolean isActive = true;

Code Example: Variables and Data Types

public class VariablesExample {
public static void main(String[] args) {
int age = 25; // Integer
double price = 19.99; // Decimal
char grade = 'A'; // Single character
String name = "John"; // String
boolean isActive = true; // Boolean

System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Name: " + name);
System.out.println("Active: " + isActive);
}
}

Expected Output:

Age: 25
Price: 19.99
Grade: A
Name: John
Active: true

2. Operators

Types of Operators in Java:

OperatorDescriptionExample
ArithmeticPerforms basic math+, -, *, /, %
RelationalCompares two values<, >, <=, >=, ==
LogicalCombines boolean conditions&&, `
AssignmentAssigns values to variables=, +=, -=, etc.

Code Example: Operators

public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 20;

// Arithmetic Operators
int sum = a + b;
int diff = b - a;

// Relational Operators
boolean isGreater = b > a;

// Logical Operators
boolean andCondition = (a < b) && (b > 15);

System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.println("Is b greater than a? " + isGreater);
System.out.println("Logical AND Condition: " + andCondition);
}
}

Expected Output:

Sum: 30
Difference: 10
Is b greater than a? true
Logical AND Condition: true

3. Input/Output

Taking Input from the User:

We use the Scanner class in Java to get input from the user.


Code Example: Input/Output

import java.util.Scanner; // Import Scanner class

public class InputOutputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object

System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a String input

System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer input

System.out.println("Hello " + name + ", you are " + age + " years old.");
}
}

Steps in NetBeans:

  1. Create a new Java file named InputOutputExample.
  2. Copy and paste the code above.
  3. Run the program and interact with the console.

Sample Console Interaction:

Enter your name: John
Enter your age: 25
Hello John, you are 25 years old.